package com.rongxun.base;

import android.app.Activity;
import android.support.annotation.NonNull;

import com.rongxun.hbwallet.R;
import com.rongxun.hbwallet.constants.ErrorCode;
import com.tbruyelle.rxpermissions2.RxPermissions;

import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;

/**
 * Created by nelon on 17-8-16.
 */

public abstract class BasePresenter<V extends IBase.IView, M extends IBase.IModel> implements IBase.IPresenter {

    protected CompositeDisposable mCompositeDisposable;
    protected V                   mView;
    private   M                   mModel;


    public BasePresenter(@NonNull V pUi) {
        mView = pUi;
    }

    public BasePresenter(@NonNull V pUi, @NonNull M pModel) {
        mView = pUi;
        mModel = pModel;
    }

    protected void unSubscribe() {
        if (mCompositeDisposable != null) {
            mCompositeDisposable.dispose();
        }
    }

    public void checkPermissions(final Activity activity, final String... permissions) {

        addSubscribe(new RxPermissions(activity).request(permissions)
                .subscribe(granted -> {
                    if (granted) {
                        getView().checkPermissionsSuccessful(permissions);
                    } else {
                        getView().showError(activity.getString(R.string.no_permission), ErrorCode.NO_PERMISSION);
                    }
                }, throwable -> {
                    throwable.printStackTrace();
                    mView.showError(throwable.getMessage(), ErrorCode.NO_PERMISSION);
                })
        );

    }


    protected void removeSubscribe(Disposable subscription) {
        if (subscription == null) {
            return;
        }
        if (mCompositeDisposable != null) {
            mCompositeDisposable.remove(subscription);
        }
    }

    protected <T extends Disposable> T addSubscribe(T subscription) {
        if (mCompositeDisposable == null) {
            mCompositeDisposable = new CompositeDisposable();
        }
        mCompositeDisposable.add(subscription);

        return subscription;
    }

    public final M getModel() {
        return mModel;
    }

    public final V getView() {
        return mView;
    }

    @Override
    public void release() {
        innerRelease();
        unSubscribe();
        if (mModel != null) {
            mModel.release();
        }
        if (mView != null) {
            mView.release();
            mView = null;
        }
        if (mModel != null) {
            mModel.release();
            mModel = null;
        }

    }

    /**
     * 其他资源的释放
     */
    protected void innerRelease() {

    }

}
